﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.ModelBinding;

namespace Morus.Presentation
{
    public sealed class HttpFileCollectionValueProvider : DictionaryValueProvider<HttpPostedFileBase[]>
    {
        private static readonly Dictionary<string, HttpPostedFileBase[]> _emptyDictionary = new Dictionary<string, HttpPostedFileBase[]>();

        public HttpFileCollectionValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
            : base(HttpFileCollectionValueProvider.GetHttpPostedFileDictionary(modelBindingExecutionContext), CultureInfo.CurrentCulture)
        {
        }

        private static Dictionary<string, HttpPostedFileBase[]> GetHttpPostedFileDictionary(ModelBindingExecutionContext modelBindingExecutionContext)
        {
            HttpFileCollectionBase files = modelBindingExecutionContext.HttpContext.Request.Files;
            if (files.Count == 0)
            {
                return HttpFileCollectionValueProvider._emptyDictionary;
            }
            List<KeyValuePair<string, HttpPostedFileBase>> list = new List<KeyValuePair<string, HttpPostedFileBase>>();
            string[] allKeys = files.AllKeys;
            for (int i = 0; i < files.Count; i++)
            {
                string text = allKeys[i];
                if (text != null)
                {
                    HttpPostedFileBase value = HttpPostedFileBaseModelBinder.ChooseFileOrNull(files[i]);
                    list.Add(new KeyValuePair<string, HttpPostedFileBase>(text, value));
                }
            }
            IEnumerable<IGrouping<string, HttpPostedFileBase>> source = list.GroupBy((KeyValuePair<string, HttpPostedFileBase> el) => el.Key, (KeyValuePair<string, HttpPostedFileBase> el) => el.Value, StringComparer.OrdinalIgnoreCase);
            return source.ToDictionary((IGrouping<string, HttpPostedFileBase> g) => g.Key, (IGrouping<string, HttpPostedFileBase> g) => g.ToArray<HttpPostedFileBase>(), StringComparer.OrdinalIgnoreCase);
        }
    }
}
